package top.dotgo.web.admin.oauth.api;

import cn.hutool.core.lang.Assert;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.dotgo.kit.CfgKit;
import top.dotgo.kit.ex.DotMsg;
import top.dotgo.web.base.BaseController;
import top.dotgo.web.base.R;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 *
 * @author jornl
 * @date 2020/3/4 1:19 星期三
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/captcha")
public class CaptchaController extends BaseController {

    private final Producer producer;

    public CaptchaController(Producer producer) {
        this.producer = producer;
    }

    /**
     * 验证码 进行验证
     *
     * @param kaptcha kaptcha
     */
    public static R checkKaptcha(String kaptcha) {
        if (!CfgKit.isKaptcha()) {
            return R.ok();
        }
        Assert.notEmpty(kaptcha, "请输入验证码");

        HttpSession session = getRequest().getSession();
        Object code = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Assert.notNull(code, "请重新获取验证码");

        //如果前置验证成功
        if (code.equals(DotMsg.SUCCESS_CODE)) {
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            return R.ok();
        }

        if (!code.equals(kaptcha)) {
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
            return R.err(DotMsg.PARAM_ERR, "验证码错误");
        }
        //标识 验证成功
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, DotMsg.SUCCESS_CODE);

        return R.ok();

    }

    /**
     * 生成验证码
     *
     * @author jornl
     * @date 2020/3/4 1:27
     */
    @GetMapping()
    public void captcha() {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        HttpSession session = request.getSession();
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String text = producer.createText();
        String capStr = text.split("=")[0];
        String result = text.split("=")[1];
        BufferedImage bi = producer.createImage(capStr + " =?");
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, result);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (IOException e) {
            log.error("验证码生成失败：e={}", e.getMessage());
        }
    }

    /**
     * 验证 验证码结果
     *
     * @param kaptcha kaptcha
     * @author jornl
     * @date 2020/3/4 1:41
     */
    @GetMapping("/check")
    public R check(@RequestParam(value = "kaptcha") @NotEmpty(message = "请输入验证码") String kaptcha) {
        return checkKaptcha(kaptcha);
    }
}
